<?php

/**
 * Class FinancingAction
 * 域名融资
 */

class FinancingAction extends BaseAction{

	protected function _initialize(){
		parent::_initialize();
		if(empty($this->user_session)){
			redirect(U('Login/index'));
		}
		$user_session = D('User')->get_user($this->user_session['uid']);
		$user_session['last'] = $this->user_session['last'];
		$this->user_session = $user_session;
		$this->assign('user_session',$this->user_session);

		//授信统计
		$pledges = D('Pledges')->where(array('uid'=>$this->user_session['uid']))->find();
		$this->assign('pledges',$pledges);

		if($this->user_session['staff_uid']){
			$escrow_staff  = M('Escrow_staff');
			$this->staff_show = $escrow_staff->where(array('id'=>$this->user_session['staff_uid']))->find();
			$this->assign('staff_show',$this->staff_show);
			if(IS_GET){
				$staff_list = $escrow_staff->field('`id`,`name`,`qq`')->select();
				$this->assign('staff_list',$staff_list);
			}
		}

		/**
		 * 还在投标的,并且当前时间大于截标日期【ExpiredAt 】表示 未借成功 自动取消
		 */
		$Db_borrows = D('Borrows');
		$borrows_con['status'] = 1;
		$borrows_con['needAmount'] = array('gt',0); //还需要借款金额大于 0
		$borrows_con['ExpiredAt'] = array('lt',date('Y-m-d',time())); //满标日期【应该使用时间戳比较】
		$borrowsList = $Db_borrows->where($borrows_con)->select();
		//echo $Db_borrows->getLastSql();

		if(!empty($borrowsList)){

			$Db_user = D('User');
			$Db_pledges = D('Pledges');
			$Db_pledge_domain = D('Pledge_domain');
			//$Db_payment_history = D('Payment_history');
			$Db_investment  = D('Investment');
			foreach($borrowsList as $key=>$borrows){
				//贷款者 --------- 不需要减去可用额度
				//$Db_user->where('`uid`='.$borrows['borrowstatus'])->setInc('now_money',$borrows['Amount']); //增加可用金额
				//$Db_user->where('`uid`='.$borrows['borrowstatus'])->setDec('freeze_money',$borrows['Amount']); //解冻资金
				$Db_pledges->where('`uid`='.$borrows['borrowstatus'])->setDec('brrowing_total',$borrows['Amount']);  //减去借贷总额
				//$Db_pledges->where('`uid`='.$borrows['borrowstatus'])->setDec('stay_total',$borrows['Amount']);  //减去待还总额
				$Db_pledges->where('`uid`='.$borrows['borrowstatus'])->setInc('credit_now',$borrows['Amount']);//增加可信总额

				//把域名状态修改回可以押质状态
				$pledge_ids = explode(',',$borrows['pids']);
				foreach($pledge_ids as $val){
					$pledge_domain_save['rz_status'] = 0;
					$Db_pledge_domain->where('`pid`='.$val)->data($pledge_domain_save)->save();
				}
				//如果有投资者
				if(!empty($borrows['inves_uids'])){
					//找出对应的投资人 进行退款 【需要判断已经收到的款】
					/**
					 * //如果有投资者
					1.退还已投资的资金
					2.修改投资状态为 0 ，表示流标
					3.增加投资人的可用资金，解冻资金，
					4.减去借出总额
					 */
					$inves_uids = explode(',',$borrows['inves_uids']);
					 
					foreach($inves_uids as $thisuid){
						$investment_con['uid'] =$thisuid;
						$investment_con['did'] = $borrows['bid'];
						$investment = $Db_investment->where($investment_con)->find();
						if(!empty($investment)){//如果有投资者
							$Db_user->where('`uid`='.$thisuid)->setInc('now_money',$investment['Amount']); //增加可用金额
							$Db_user->where('`uid`='.$thisuid)->setDec('freeze_money',$investment['Amount']); //解冻资金
							$Db_pledges->where('`uid`='.$thisuid)->setDec('lend_total',$investment['Amount']);  //减去借出总额
							$investment_save['status']       = 0;
							$Db_investment->where($investment_con)->data($investment_save)->save();
						}
					}
				}

				//把 $Db_borrows 的 $borrows['borrowstatus'] 这个人的status 修改为 4 过期
				$borrows_save['status'] = 4;
				$borrows_save['bid'] = $borrows['bid'];
				$Db_borrows->data($borrows_save)->save();
			}
		}


		/**
		 * 逾期处理，
		借款逾期了怎么办？
		1、借款期内，如果借入者未在规定的时间偿还借款利息和管理费用，诚借平台将加收所欠利息的0.5%/日作为违约金；
		2、借款合同到期后，如果借入者未能按时偿还本金、利息和管理费用，诚借平台将加收所欠款项的0.5%/日作为违约金，
		 * 另需与诚借平台客服联系，约定还款日期，诚借平台将保留对质押物依法处分用以清偿债务的权利。
		如果逾期还款，诚借平台有权根据具体情况将用户列入不良信用客户，诚借平台强烈呼吁借款用户尽量避免逾期还款，一旦发生逾期请尽快还清贷款。

		 * 找出还在还款中，但是已经过了还款期限或者合同到期了 [合同到期《 当前时间]
		 *  A 上一次还款时间：2016-02-02
		 *  B 本次查询时间：2016-02-05
		 *   A  < B 有逾期
		 *
		 *  A 上一次还款时间：2016-02-02
		 *  B 本次查询时间：2016-02-05
		 *
		 *  A < B 已经逾期，逾期 3天
		 *
		 * 合同到期 2016-02-05    《 当前查询时间
		 * 合同结束逾期
		 */

		$check_now_date = date('Y-m-d',time()); //当前查询时间：YYYY-MM-DD
		$borrows_condition['NextRepayDate'] = array('lt',$check_now_date);
		$borrows_condition['contractExpire'] = array('lt',$check_now_date);
		$borrows_condition['_logic'] = 'or';
		$borrows_where['_complex'] = $borrows_condition;
		$borrows_where['status'] = 2;
		$borrowsOverList = $Db_borrows->where($borrows_where)->select();

		if(!empty($borrowsOverList)){ //已经是逾期或者到期的列表
			$Db_breachs = D('Breachs');

			foreach($borrowsOverList as $key=>$borrows){
				 if(($borrows['NextRepayDate'] < $check_now_date) && $check_now_date < $borrows['contractExpire'] ){
				 //应还时间内，还是还没有到期 【    应该还款时间 《当前查询时间  《 合同到期时间】
					/** 每次违约记录一次
					 * 诚借平台将加收所欠利息的0.5%/日作为违约金；
					 * 本月应还金额 * 0.005 * 逾期天数 = 违约金
					 */

					 $breachs_add['status'] = 1;
					 $breachDays = getBetweenTwoDate($borrows['NextRepayDate'] ,$check_now_date);
					 $breachMoney = $borrows['myfk'] * RI_LIXI * $breachDays;
					 //增加违约金
					 $Db_borrows->where('`bid`='.$borrows['bid'])->setInc('breachMoney',$breachMoney);
					 //修改一下一次应还时间 =  本次应该  + 周期
					 if($borrows['LoanCycleMonth'] > 1){ //周期必须是2个月以上
						 $days = $borrows['LoanCycleMonth'] * 30;
					 }
					 $borrows_save_data['NextRepayDate'] = date('Y-m-d',strtotime("{$borrows['NextRepayDate']}  + $days day"));

					 $Db_borrows->where('`bid`='.$borrows['bid'])->save($borrows_save_data);

				 }else if($borrows['contractExpire'] < $check_now_date  ){
				 //合同已经到期 【  合同到期时间 《 当前查询出时间】
					/**
					 * 按时偿还本金、利息和管理费用，诚借平台将加收所欠款项的0.5%/日作为违约金
					（（本金+总利息+总管理费） - （ 每月还款金额 * 已经还款期数 ） * 0.005 * 违约天数
					 */
					 $breachs_add['status'] = 2;
					 $breachDays = getBetweenTwoDate($borrows['contractExpire'] ,$check_now_date);
					 $breachMoney = (($borrows['zhhk'] + $borrows['zlx'] + $borrows['zglf']) - ($borrows['myfk']) * $borrows['periodsed']) * RI_LIXI *
						 $breachDays;
					// echo "违约天数：{$breachDays}天 ---- 违约金额：{$breachMoney} <br/>";
				 }
				$breachs_add['breachTiem'] = date('Y-m-d',time());
				$breachs_add['breachDays'] = $breachDays;
				$breachs_add['breachMoney'] = $breachMoney;
				$breachs_add['uid'] = $borrows['borrowstatus'];
				$breachs_add['bid'] = $borrows['bid'];

				//防止同一天刷新多次记录无用
				$breach_condition['uid'] = $borrows['borrowstatus'];
				$breach_condition['bid'] = $borrows['bid'];
				$breachTime = date('Y-m-d',time());
				$breach_condition['breachTiem'] = array('eq',$breachTime);
				$breachs = $Db_breachs->where($breach_condition)->find();
				//违约记录
                if(!empty($breachs)) $Db_breachs->data($breachs_add)->add();

			}
		}

	}
	public function _empty(){
		$this->display();
	}

	public function index(){
		$Db_id_card  = D('Id_card');
		$condition_uid = array('uid'=>$this->user_session['uid']);
		$result_idcard = $Db_id_card->field('`card_id`,`status`')->where($condition_uid)->find();
		$this->assign('result_idcard',$result_idcard);
		$Db_loan_trade_pass = D('Loan_trade_pass');
		$trade_pass = $Db_loan_trade_pass->where('`uid`='.$this->user_session['uid'])->getField('status');
		$this->assign('is_set_trade_pass',$trade_pass);
		$this->display();
	}

	//会员
	public function level(){
		$this->display();
	}
}